package net.starwifi.duobao.web;


import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.CaptchaService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.RSAService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Controller - 共用
 * 
 * @author ruoo
 * @version 1.0
 */
@Controller("wapCommonController")
@RequestMapping("/common")
public class CommonController {

	@Autowired
	private RSAService rsaService;

	@Autowired
	private CaptchaService captchaService;


	/**
	 * 验证码
	 */
	@RequestMapping(value = "/captcha", method = RequestMethod.GET)
	public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (StringUtils.isEmpty(captchaId)) {
				captchaId = request.getSession().getId();
		}
		String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse().toString();
		String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse().toString();
		response.addHeader(pragma, value);
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream servletOutputStream = null;
		try {
			servletOutputStream = response.getOutputStream();
			BufferedImage bufferedImage = captchaService.buildImage(captchaId);
			ImageIO.write(bufferedImage, "jpg", servletOutputStream);
			servletOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(servletOutputStream);
		}
	}



	/**
	 * 公钥
	 */
	@RequestMapping(value = "/public_key", method = RequestMethod.GET)
	public @ResponseBody
	Object publicKey(HttpServletRequest request) {
		final RSAPublicKey publicKey = rsaService.generateKey(request);
		return Message.createMessage(Message.success("success"), new HashMap<String, Object>() {{
			put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
			put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));

		}});
	}

	/** 手机号码合法性*/
	public static boolean isMobileNO(String mobiles){
		Pattern p = Pattern.compile("^((133|153|180|181|189|177))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}


	/**
	 * 校验短信验证码.
	 * @param phone 手机号码
	 */
	@RequestMapping(value = "/setPass")
	public @ResponseBody Object setPass(String phone,String uuid,HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String uuidKey="sms_findPass_"+phone+"_"+"success";
		if(request.getSession().getAttribute(uuidKey)==null){
			return Message.error("无验证授权");
		}
		String sessionCode=(String)request.getSession().getAttribute(uuidKey);
		if(!sessionCode.equals(uuid)){
			return Message.error("无验证授权");
		}
		String password = rsaService.decryptParameter("pass", request);
		Member member=memberService.findByMobile(phone);
		if(member==null){
			return Message.error("用户不存在");
		}
		String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
		member.setSalt(salt);
		member.setPassword(DigestUtils.md5Hex(password + salt));
		memberService.update(member);
		return Message.success("密码修改成功");
	}

	@Autowired
	MemberService memberService;

	/**
	 * 错误提示
	 */
	@RequestMapping("/error")
	public String error() {
		return "/common/error";
	}

	/**
	 * 资源不存在
	 */
	@RequestMapping("/resource_not_found")
	public String resourceNotFound(HttpServletRequest request) {

		return "/common/resource_not_found";
	}

	/**
	 * 资源不存在
	 */
	@RequestMapping("/401")
	public String unAuth(HttpServletRequest request) {

		return "/common/401";
	}

	/**
	 * 资源不存在
	 */
	@RequestMapping("/403")
	public String unAuth3(HttpServletRequest request) {

		return "/common/403";
	}




}